package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandsByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
            //设置分页
            PageHelper.startPage(page,rows);

            //设置过滤条件
            Example example = new Example(Brand.class);
            if(StringUtils.isNotBlank(key)){
                example.createCriteria().andLike("name","%"+key+"%").orEqualTo("letter",key);
            }

            //设置排序
            if(StringUtils.isNotBlank(sortBy)){
                example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
            }

            //查询
            Page<Brand> pageInfo= (Page<Brand>) brandMapper.selectByExample(example);

            //返回查询结果
            return new PageResult<Brand>(pageInfo.getTotal(),pageInfo.getPages(),pageInfo.getResult());
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌信息
        brandMapper.insert(brand);

        // 新增品牌和分类中间表
        cids.forEach(cid->{
            brandMapper.insertCategoryBrand(cid,brand.getId());
        });
    }

    public void updateBrandById(Brand brand, List<Long> cids) {
        //修改品牌信息
        brandMapper.updateByPrimaryKeySelective(brand);

        brandMapper.deleteCategoryBrandById(brand.getId());
        //修改品牌和分类中间表
        cids.forEach(cid->{
            brandMapper.insertCategoryBrand(cid,brand.getId());
        });
    }

    public void deleteBrandById(Long id) {
        brandMapper.deleteByPrimaryKey(id);
        brandMapper.deleteCategoryBrandById(id);
    }

    public List<Brand> queryBrandsByCid(Long cid) {
        return brandMapper.queryBrandsByCid(cid);
    }

    public List<Brand> queryBrandByIds(List<Long> ids) {
        return brandMapper.selectByIdList(ids);
    }

    public Brand queryBrandById(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }
}
